package com.hanbang.chu_xing_gao_zhao.view_dynamic;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hanbang.chu_xing_gao_zhao.adapter.FaceAdapter;
import com.hanbang.chu_xing_gao_zhao.application.HttpInterfaces;
import com.hanbang.chu_xing_gao_zhao.application.MyApplication;
import com.hanbang.chu_xing_gao_zhao.base.BaseActivity;
import com.hanbang.chu_xing_gao_zhao.myview.MyDialog;
import com.hanbang.chu_xing_gao_zhao.myview.MyDialog.MODE;
import com.hanbang.chu_xing_gao_zhao.utils.MyLocationUtils;
import com.hanbang.chu_xing_gao_zhao.utils.MyLocationUtils.locationCallback;
import com.hanbang.chu_xing_gao_zhao.utils.MyLog;
import com.hanbang.chu_xing_gao_zhao.utils.MyRequestCallBack;
import com.hanbang.chu_xing_gao_zhao.utils.MySharedPreferences;
import com.hanbang.chu_xing_gao_zhao.utils.MyToast;
import com.hanbang.chu_xing_gao_zhao.utils.SystemTools;
import com.hanbang.chu_xing_gao_zhao.utils.UiUtils;
import com.hanbang.cxgz_2.R;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

/**
 * 发布动态
 */
public class DynamicIssueActivity extends BaseActivity {
	/** 显示表情 */
	private GridView faceGridView;
	/** 表情适配器 */
	private FaceAdapter faceAdapter;
	/** 打开与关闭表情 */
	private LinearLayout face;
	/** 编辑框 */
	private EditText etIssue;

	/** 我的位置 */
	private String myLocation = "";

	/** 获取位置 */
	private MyLocationUtils getLocation;

	/** 显示位置 */
	private TextView tvLocation;

	/** 通知好友 */
	// private TextView addFriend;

	/** 相册路径 */
	private String path = "";

	/** 相机路径 */
	private String camerapath = "";

	/** 动态图片展示 */
	private ArrayList<String> pictureShowData;

	/** 图片展示 */
	private GridView pictureGridView;

	/** 图片适配器 */
	private PictureShowAdapter pAdapter;

	private Button showLocation;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dynamic_issue);

		initView();
		setOnClickListener();
		getLocation(true);
		setPictureAdapter();

	}

	/**
	 * 初始化view
	 */
	private void initView() {
		// addFriend = (TextView) findViewById(R.id.tv_dynamic_issue_addFriend);
		faceGridView = (GridView) findViewById(R.id.gv_dynamic_issue_gridView);
		faceAdapter = new FaceAdapter(this);
		faceGridView.setAdapter(faceAdapter);
		face = (LinearLayout) findViewById(R.id.dynamic_issue_face);

		etIssue = (EditText) findViewById(R.id.et_dynamic_issue);
		tvLocation = (TextView) findViewById(R.id.tv_dynamic_issue_location);
		showLocation = (Button) findViewById(R.id.btn_dynamic_issue_location);
		getLocation = new MyLocationUtils(this);

		pictureShowData = new ArrayList<>();
		pictureGridView = (GridView) findViewById(R.id.gv_dynamic_issue_pictureShow);

	}

	/**
	 * 获取位置
	 */
	private void getLocation(boolean showLocation) {

		if (showLocation) {

			// 获取定位

			getLocation.setOnClickCallback(new locationCallback() {
				@Override
				public void onClick(String location, double longitude, double latitude) {
					myLocation = location;

					MyLog.i("text", "000*我的当前位置**" + myLocation + "经度：" + longitude + "纬度：" + latitude);
					addData(myLocation);

				}
			});

		} else {
			addData("");
		}
	}

	/**
	 * 添加数据
	 */
	private void addData(String location) {
		tvLocation.setText(location);
	}

	/**
	 * 为图片显示添加适配器
	 */
	private void setPictureAdapter() {
		pAdapter = new PictureShowAdapter(this, pictureShowData);
		pictureGridView.setAdapter(pAdapter);

	}

	/**
	 * 设置点击事件
	 */
	private void setOnClickListener() {
		face.setOnClickListener(onClickListener);
		showLocation.setOnClickListener(onClickListener);

		// addFriend.setOnClickListener(onClickListener);
		// 发布添加监听
		((TextView) findViewById(R.id.tv_bar_top_conver_classify_title3)).setOnClickListener(onClickListener);

		/**
		 * 点击表情的监听
		 */
		faceGridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// 获取表情的名字
				String emotionName = faceAdapter.getItem(position);
				// 获取当前光标位置,在指定位置上添加表情图片文本
				int curPosition = etIssue.getSelectionStart();

				// 把所有的内容变成字符串
				StringBuilder sb = new StringBuilder(etIssue.getText().toString());
				// 把内容插入在最后面
				sb.insert(curPosition, emotionName);

				if (sb.length() >= 140) {

					MyToast.show(DynamicIssueActivity.this, "注:动态发布最多限制140汉字", Toast.LENGTH_SHORT);

					return;

				}

				// 特殊文字处理,将表情等转换一下
				etIssue.setText(ImageStringUtils.getEmotionContent(DynamicIssueActivity.this, etIssue, sb.toString()));

				// 将光标设置到新增完表情的右侧
				etIssue.setSelection(curPosition + emotionName.length());
			}
		});

		showLocation.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (v.isSelected()) {
					v.setSelected(false);
					getLocation(false);
					showLocation.setBackgroundResource(R.drawable.bg_corners12_graydd_background);
					if (getLocation != null) {
						getLocation.stop();
					}
				} else {
					v.setSelected(true);
					getLocation(true);
					showLocation.setBackgroundResource(R.drawable.bg_corners12__yellow_background);
					if (getLocation != null) {
						getLocation.initLocation();
					}
				}

			}
		});

	}

	/**
	 * 处理监听
	 */
	@SuppressWarnings("unused")
	private OnClickListener onClickListener = new OnClickListener() {
		Intent intent = new Intent();

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			// 打开关闭表情库
			case R.id.dynamic_issue_face:

				if (faceGridView.getVisibility() == View.GONE) {
					faceGridView.setVisibility(View.VISIBLE);
				} else if (faceGridView.getVisibility() == View.VISIBLE) {
					faceGridView.setVisibility(View.GONE);
				}
				break;
			// 发布
			case R.id.tv_bar_top_conver_classify_title3:
				issue();
				break;

			default:
				break;
			}

		}

	};

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		/**
		 * 获取图片地址
		 */
		if (requestCode == 999 && resultCode == -1) {
			Uri uri = data.getData();
			path = SystemTools.getPath(DynamicIssueActivity.this, uri);
			pictureShowData.add(path);
			pAdapter.notifyDataSetChanged();
			MyLog.i("text", "*111**" + path);// *****

			// 获取拍照的图片路径
		} else if (requestCode == 998 && resultCode == -1) {
			File fDir = new File(MyApplication.picFilepath);
			// 判断文件夹是否存在
			if (fDir.exists() || fDir.mkdirs()) {
				File cameraFile = new File(fDir, camerapath);
				// 判断文件时是否存在
				if (cameraFile.exists()) {
					camerapath = cameraFile.getPath();

					pictureShowData.add(camerapath);
					pAdapter.notifyDataSetChanged();
					 MyLog.i("text", "*222**" + cameraFile.getPath());// *****

				} else {
					MyToast.show(DynamicIssueActivity.this, "获取照片失败！", Toast.LENGTH_SHORT);
				}
			} else {
				MyToast.show(DynamicIssueActivity.this, "获取照片失败！", Toast.LENGTH_SHORT);
			}
		}

	};

	/**
	 * 发布
	 */
	private void issue() {
		/** 获得手机品牌加型号加 */
		String phoneName = android.os.Build.BRAND + ":" + android.os.Build.MODEL;

		if (etIssue.length() == 0) {
			MyToast.show(DynamicIssueActivity.this, "内容不可为空", Toast.LENGTH_SHORT);
			return;

		}
		RequestParams params = new RequestParams();
		params.addBodyParameter("telphone", MySharedPreferences.getSharedPreferencesKeyAndValue(
				DynamicIssueActivity.this, MySharedPreferences.USER_DATA, "tlephone"));
		params.addBodyParameter("password", MySharedPreferences.getSharedPreferencesKeyAndValue(
				DynamicIssueActivity.this, MySharedPreferences.USER_DATA, "password"));
		params.addBodyParameter("text", etIssue.getText().toString());
		params.addBodyParameter("phone", phoneName);
		params.addBodyParameter("position", tvLocation.getText().toString());

		for (int i = 0; i < pictureShowData.size(); i++) {

			File picture = new File(pictureShowData.get(i));

			if (picture.exists()) {
				params.addBodyParameter("img_url" + i, picture);
			}
		}

		// @通知好友暂时不做
		// params.addBodyParameter("at", "@8888");

		httpUtils.send(HttpMethod.POST, HttpInterfaces.Feed_Add, params,
				new MyRequestCallBack<String>(this, "发送动态...") {
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						super.onSuccess(responseInfo);

						try {
							JSONObject json = new JSONObject(responseInfo.result);
							int statrs = json.getInt("Result");
							String msg = json.getString("Msg");

							if (statrs == 0) {

								MyToast.show(DynamicIssueActivity.this, "发送成功", Toast.LENGTH_SHORT);
								Intent intent = new Intent();
								intent.setClass(DynamicIssueActivity.this, DynamicActivity.class);
								startActivity(intent);

							} else {
								MyToast.show(DynamicIssueActivity.this, msg, Toast.LENGTH_SHORT);
							}

						} catch (Exception e) {
							e.printStackTrace();
							MyToast.show(DynamicIssueActivity.this, "发送失败", Toast.LENGTH_LONG);
						}
					}

				});

	}

	@Override
	protected void onResume() {
		setTitleMore(View.GONE, View.GONE, "取消", "发布动态", "发布", null);
		// 返回的调用
		setBackArrows(findViewById(R.id.tv_bar_top_conver_classify_title1));
		// 重新设置控件的对齐方式
		((TextView) findViewById(R.id.tv_bar_top_conver_classify_title1)).setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
		((TextView) findViewById(R.id.tv_bar_top_conver_classify_title3)).setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
		super.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (getLocation != null) {

			getLocation.stop();
		}
	}

	@Override
	protected void onDestroy() {

		super.onDestroy();

	}

	/**
	 * gridview adapter
	 * 
	 * @author Administrator
	 */
	class PictureShowAdapter extends BaseAdapter {
		public ArrayList<String> list;
		private LayoutInflater inflater;

		public PictureShowAdapter(Context context, ArrayList<String> list) {
			this.inflater = LayoutInflater.from(context);

			if (list != null) {
				this.list = list;

			} else {
				list = new ArrayList<String>();

			}
		}

		@Override
		public int getCount() {
			return list.size() + 1;
		}

		@Override
		public String getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {

			UiUtils.applyFont(convertView);
			ViewHolder viewHolder;
			if (convertView == null) {// 是空加载
				convertView = inflater.inflate(R.layout.item_dycamic_horizontal_listview_delect, null);
				viewHolder = new ViewHolder();
				viewHolder.picture = (ImageView) convertView.findViewById(R.id.iv_item_shoppingcart_recommend_image);
				viewHolder.deletePicture = (ImageView) convertView
						.findViewById(R.id.iv_item_shoppingcart_recommend_delete);
				convertView.setTag(viewHolder);
			} else {// 不是空复用

				viewHolder = (ViewHolder) convertView.getTag();
			}

			// 添加加号
			if (position == list.size()) {
				viewHolder.picture.setPadding(10, 70, +70 + 60, 70);
				viewHolder.picture.setImageResource(R.drawable.add);
				viewHolder.deletePicture.setVisibility(View.GONE);
				// 添加图片
			} else {
				viewHolder.picture.setPadding(0, 0, 0, 00);
				viewHolder.deletePicture.setVisibility(View.VISIBLE);
				bitmapUtils.display(viewHolder.picture, list.get(position));
			}

			viewHolder.picture.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					if (pictureShowData.size() == 9) {
						MyToast.show(DynamicIssueActivity.this, "图片最多上传9张", Toast.LENGTH_SHORT);
						return;
					}
					// 新建一个dialog 对话框
					MyDialog myDialog = new MyDialog(DynamicIssueActivity.this, R.style.about_me_dialog, MODE.HEAD);
					// 添加图片的监听
					myDialog.setOnClickCallback(new com.hanbang.chu_xing_gao_zhao.myview.MyDialog.OnClickCallback() {

						@Override
						public void onClick(MyDialog dialog, Object number, Object content) {

							// 拍照
							if ((Integer) number == 1) {
								File fDir = new File(MyApplication.picFilepath);
								camerapath = System.currentTimeMillis() + ".jpg";
								if (fDir.exists() || fDir.mkdirs()) {
									File cameraFile = new File(fDir, camerapath);
									if (!cameraFile.exists()) {
										try {
											cameraFile.createNewFile();
										} catch (IOException e) {
											e.printStackTrace();
										}
									}

									Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
									intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
									startActivityForResult(intent, 998);
								}
								// 相册选择
							} else if ((Integer) number == 2) {
								// 获取相册
								Intent intent = new Intent();
								intent.setType("image/*");
								intent.setAction(Intent.ACTION_GET_CONTENT);
								intent.putExtra("return-data", true);
								startActivityForResult(intent, 999);
							}

						}
					});
					myDialog.show();
				}
			});

			// 删除图片
			viewHolder.deletePicture.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					pictureShowData.remove(position);
					pAdapter.notifyDataSetChanged();

				}
			});

			return convertView;
		}

		class ViewHolder {// 进行缓存保存
			private ImageView picture; // 图片
			private ImageView deletePicture; // 删除 图片

		}

	}
}